import { reqGetCode, reqUserInfo, reqUserLogin, reqUserRegister, reqLogout } from '@/api'
import { getToken, removeToken, setToken } from '@/utils/token'


let state = {
    code: '',
    token: getToken(),
    userInfo: {}
}
let actions = {
    //获取验证码
    async getCode ({ commit }, phone) {
        let res = await reqGetCode(phone)
        if (res.code == 200) {
            commit('GETCODE', res.data)

            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户注册
    async userRegisters ({ commit }, user) {
        let res = await reqUserRegister(user);
        console.log(res);
        if (res.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //登录业务
    async userLogin ({ commit }, data) {
        let res = await reqUserLogin(data);
        if (res.code == 200) {
            commit('USERLOGIN', res.data.token)
            // 持久化存储
            setToken(res.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //获取用户信息
    async getUserInfo ({ commit }) {
        let res = await reqUserInfo()
        if (res.code == 200) {
            commit('GETUSERINFO', res.data)
            return 'ok'
        } else {
            Promise.reject(new Error('faile'))
        }
    },
    //退出登录
    async userLogout ({ commit }) {
        let res = await reqLogout()
        if (res.code == 200) {
            commit('CLEAR')
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }
}
let mutations = {
    GETCODE (state, code) {
        state.code = code
    },
    USERLOGIN (state, token) {
        state.token = token
    },
    GETUSERINFO (state, userInfo) {
        state.userInfo = userInfo
    },
    CLEAR (state) {
        state.code = '',
            state.userInfo = {},
            removeToken()
    }
}
let getters = {}
export default {
    state, actions, mutations, getters
}